#include "zhi.h"
//为运行函数准备桢栈
void 为运行函数准备桢栈(线程对象S* objThread, 闭包对象S* objClosure, Value* stackStart) {
   ASSERT(objThread->frameCapacity > objThread->usedFrameNum, "frame not enough!!");   
   //objThread->usedFrameNum是最新可用的frame
   调用框架S* frame = &(objThread->frames[objThread->usedFrameNum++]);

   //thread中的各个frame是共享thread的stack
   //frame用frame->stackStart指向各自frame在thread->stack中的起始地址
   frame->stackStart = stackStart;
   frame->closure = objClosure;
   frame->ip = objClosure->fn->instrStream.数据缓冲区;
}

//重置thread
void 重置线程(线程对象S* objThread, 闭包对象S* objClosure) {
   objThread->esp = objThread->stack;  
   objThread->openUpvalues = NULL;
   objThread->caller = NULL;
   objThread->errorObj = VT_TO_VALUE(值类型_空);
   objThread->usedFrameNum = 0;

   ASSERT(objClosure != NULL, "objClosure is NULL in function 重置线程");
   为运行函数准备桢栈(objThread, objClosure, objThread->stack);
}

//新建线程
线程对象S* 新建线程(虚拟机* 虚拟机S, 闭包对象S* objClosure) {
   ASSERT(objClosure != NULL, "objClosure is NULL!");

   调用框架S* frames = 分配数组内存M(虚拟机S, 调用框架S, INITIAL_FRAME_NUM);

   //加1是为接收者的slot
   uint32_t stackCapacity = 大于等于v最近的2次幂(objClosure->fn->maxStackSlotUsedNum + 1);  
   Value* newStack = 分配数组内存M(虚拟机S, Value, stackCapacity); 

   线程对象S* objThread = 分配指定类型的内存块M(虚拟机S, 线程对象S);
   初始化对象头(虚拟机S, &objThread->objHeader, 对象类型_线程, 虚拟机S->threadClass);

   objThread->frames = frames;
   objThread->frameCapacity = INITIAL_FRAME_NUM;
   objThread->stack = newStack;
   objThread->stackCapacity = stackCapacity;

   重置线程(objThread, objClosure);
   return objThread;
}
